import { request } from "../../request/index.js";
//Page Object
Page({
  data: {
    textVal: "",
    addressId: undefined,
  },
  onShow: function () {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1];
    let options = currentPage.options;
    const { addressId } = options;
    this.setData({ addressId });
    console.log("addressId", addressId);
  },
  // 添加收货地址还是修改收货地址
  changeAddress() {
    const {addressId} = this.data;
    if (addressId) {
      this.editAddress(addressId);
    } else {
      this.addAddress();
    }
  },
  // 文本域的输入的事件
  handleTextInput(e) {
    this.setData({
      textVal: e.detail.value,
    });
  },
  // 添加收货地址
  async addAddress() {
    // 1 获取文本域的内容 图片数组
    const { textVal } = this.data;
    // 2 合法性的验证
    if (!textVal.trim()) {
      // 不合法
      wx.showToast({
        title: "输入不合法",
        icon: "none",
        mask: true,
      });
      return;
    }
    try {
      const res = await request({
        url: "/v2/address",
        method: "POST",
        data: { address: textVal },
      });
      wx.navigateTo({
        url: "/pages/address/index",
      });
      console.log("res", res);
    } catch (error) {
      console.log(error);
    }
  },
  // 修改收货地址
  async editAddress(id) {
    // 1 获取文本域的内容 图片数组
    const { textVal } = this.data;
    // 2 合法性的验证
    if (!textVal.trim()) {
      // 不合法
      wx.showToast({
        title: "输入不合法",
        icon: "none",
        mask: true,
      });
      return;
    }
    try {
      const res = await request({
        url: "/v2/address",
        data: { id, address: textVal },
        method: "PUT"
      });
      wx.navigateTo({
        url: "/pages/address_list/index",
      });
      console.log('res',res);
    } catch (error) {
      console.log(error);
    }
  },
});
